package com.example.streamdemo;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.Input;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.cloud.stream.function.StreamBridge;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.SubscribableChannel;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;

@Slf4j
//@RestController
public class IntegrationAnnotation {

    private final StreamBridge streamBridge;

    public IntegrationAnnotation(StreamBridge streamBridge) {
        this.streamBridge = streamBridge;
    }


    /************************************send data ************************************/
    @PostMapping(path = "/{dest}", consumes = "*/*")
    @ResponseStatus(HttpStatus.ACCEPTED)
    public void handleRequest(@PathVariable("dest") String dest,
                              @RequestBody String body,
                              @RequestHeader(HttpHeaders.CONTENT_TYPE) Object contentType) {
        streamBridge.send(dest, MessageBuilder.createMessage(body, new MessageHeaders(Collections.singletonMap(MessageHeaders.CONTENT_TYPE, contentType))));
    }


    public interface MySink {
        /*********************************动态通道选择示例******************************/
        String DYNAMIC1_CHANNEL = "dynamic1-channel";
        String DYNAMIC2_CHANNEL = "dynamic2-channel";

        @Input(DYNAMIC1_CHANNEL)
        SubscribableChannel dynamic1Input();

        @Input(DYNAMIC2_CHANNEL)
        SubscribableChannel dynamic2Input();
    }


    @EnableBinding(MySink.class)
    public class SinkReceiver {
        /*********************************动态通道选择示例******************************/
        @StreamListener(value = MySink.DYNAMIC1_CHANNEL)
        public void dynamic1Receiver(@Payload SecurityProperties.User user) {
            log.info("Received-{} from {} channel age: {}", "active", MySink.DYNAMIC1_CHANNEL, user.toString());
        }

        @StreamListener(value = MySink.DYNAMIC2_CHANNEL)
        public void dynamic2Receiver(@Payload SecurityProperties.User user) {
            log.info("Received-{} from {} channel age: {}", "active", MySink.DYNAMIC2_CHANNEL, user.toString());
        }
    }


}
